import { Resp } from '../interface/common.interface'
import type { Context, Next } from 'koa'

const defaultValue = { code: 200, msg: '操作成功' }

// 请求成功时返回
const normall = async (ctx: Context, next: Next): Promise<void> => {
  ctx.echo = (obj: Resp = defaultValue): void => {
    const { code = 200, msg = '操作成功', data, ...res } = obj
    let respData = { ...res }
    if (!Object.keys(respData).length) respData = data
    ctx.body = {
      code,
      msg,
      data: respData,
    }
  }
  await next()
}

// 请求失败时返回
const errorFun = async (ctx: Context, next: Next): Promise<void> => {
  ctx.error = (obj: Resp): void => {
    const { code = 201, msg = '操作失败', data = undefined } = obj
    ctx.app.emit('error', { code, msg, data }, ctx)
  }
  await next()
}

export default {
  normall,
  errorFun,
}
